{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Interactive Polynomial Fitting"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "This notebook is best experienced when exported to a Python script and run from the command line."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {},
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "import numpy.linalg as la\n",
        "\n",
        "from matplotlib.pyplot import (\n",
        "    clf, plot, show, xlim, ylim,\n",
        "    get_current_fig_manager, gca, draw, connect)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Run this cell to play with the node placement toy:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {},
      "outputs": [],
      "source": [
        "x_points = []\n",
        "y_points = []\n",
        "deg = [1]\n",
        "\n",
        "def update_plot():\n",
        "    clf()\n",
        "    xlim([-1, 1])\n",
        "    ylim([-1.5, 1.5])\n",
        "    gca().set_autoscale_on(False)\n",
        "    plot(x_points, y_points, 'o')\n",
        "\n",
        "    if len(x_points) >= deg[0]+1:\n",
        "        eval_points = np.linspace(-1, 1, 500)\n",
        "        poly = np.poly1d(np.polyfit(\n",
        "            np.array(x_points),\n",
        "            np.array(y_points), deg[0]))\n",
        "        plot(eval_points, poly(eval_points), \"-\")\n",
        "\n",
        "\n",
        "def click(event):\n",
        "    tb = get_current_fig_manager().toolbar\n",
        "    if event.button == 1 and event.inaxes and tb.mode == '':\n",
        "        x_points.append(event.xdata)\n",
        "        y_points.append(event.ydata)\n",
        "\n",
        "    if event.button == 3 and event.inaxes and tb.mode == '':\n",
        "        if len(x_points) >= deg[0]+2:\n",
        "            deg[0] += 1\n",
        "\n",
        "    update_plot()\n",
        "    draw()\n",
        "\n",
        "update_plot()\n",
        "connect('button_press_event', click)\n",
        "show()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": true
      },
      "outputs": [],
      "source": []
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.7.2"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 1
}